package com.cetc.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @Classname LambdaTest02
 * @Description 测试JAVA8四大内置函数式接口
 * @Date 2022/12/23 20:19
 * @Created by louzhuangxi
 */
public class LambdaTest02 {
    /**
     * 消费型接口 Consumer<T> void accept(T t)
     * 供给型接口 Supplier<T> T get()
     * 函数型接口 Function<T,R> R apply(T t)
     * 断定型接口 Predicate<T> boolean test(T t)
     */

    @Test
    public void test01() {
        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("学习太累了，放松一下～～～");
            }
        });

        System.out.println("*************");
        happyTime(500, aDouble -> System.out.println("学习太累了，放松一下～～～"));
    }

    public void happyTime(double money, Consumer<Double> con) {
        con.accept(money);
    }

    @Test
    public void test02() {
        List<String> aList = Arrays.asList("南京", "北京", "上海");
        List<String> filterString = filterString(aList, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });
        System.out.println(filterString);

        System.out.println("*************************");
        List<String> filterString1 = filterString(aList, s -> s.contains("京"));
        System.out.println(filterString1);
    }

    public List<String> filterString(List<String> strList, Predicate<String> pre) {
        List<String> aList = new ArrayList<>();
        for (String str : strList) {
            if (pre.test(str)) {
                aList.add(str);
            }
        }
        return aList;
    }

    @Test
    public void test03() {
        double money = getMoney(new Supplier<Double>() {
            @Override
            public Double get() {
                return 1.2;
            }
        });
        System.out.println(money);

        System.out.println("***********************");
        double money1 = getMoney(() -> 1.2);
        System.out.println(money1);
    }

    double getMoney(Supplier<Double> supplier) {
        return supplier.get();
    }

    @Test
    public void test04() {
        String res = execute(3, new Function<Integer, String>() {
            @Override
            public String apply(Integer i) {
                return "success";
            }
        });
        System.out.println(res);
        System.out.println("****************************");

        String res1 = execute(3, i -> "success");
        System.out.println(res1);
    }

    String execute(int param1, Function<Integer, String> function) {
        return function.apply(param1);
    }
}
